package com.yao.code;

import com.yao.tool.ListNode;
import com.yao.tool.Node;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author yaoquanwei
 * @date 2021/8/9 9:22
 */
public class Code210809 {

    /**
     * 剑指offer 6.从尾到头打印链表
     *
     * @param head
     * @return
     */
    public static int[] reversePrint(ListNode head) {
        int size = 0;
        ListNode node = head;
        while (node != null) {
            size++;
            node = node.next;
        }
        int[] res = new int[size];
        node = head;
        size--;
        while (node != null) {
            res[size--] = node.val;
            node = node.next;
        }
        return res;
    }

    /**
     * 剑指offer 24.反转链表
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        ListNode node, newHead = null;
        while (head != null) {
            node = head;
            head = head.next;
            node.next = newHead;
            newHead = node;
        }
        return newHead;
    }

    /**
     * 剑指offer 35.复杂链表的复制
     * @param head
     * @return
     */
    public static Node copyRandomList(Node head) {
        if (head == null) {
            return head;
        }
        Node tem = head;
        // 先复制链表
        while (tem != null) {
            Node copyNode = new Node(tem.val);
            copyNode.next = tem.next;
            tem.next = copyNode;
            tem = tem.next.next;
        }
        // 复制链表的random指针
        tem = head;
        while (tem != null) {
            if (tem.random != null) {
                tem.next.random = tem.random.next;
            }
            tem = tem.next.next;
        }

        //一分为二
        Node resNode = head.next;
        tem = head;
        Node copyNode = head.next;
        while (tem != null) {
            tem.next = tem.next.next;
            tem = tem.next;
            if (copyNode.next != null) {
                copyNode.next = copyNode.next.next;
                copyNode = copyNode.next;
            }
        }
        return resNode;
    }

    public static void main(String[] args) {

    }

}
